var _T = {Ui:{}, Ajax:{}, elements:{}, formFields:{}};

(function () {

    _T.get = function (tid) {
        return _T.elements[tid];
    };

    _T.apply = function (object, config, defaults) {
        if (defaults) {
            _T.apply(object, defaults);
        }

        if (object && config && typeof config === 'object') {
            for (var i in config) {
                object[i] = config[i];
            }
        }

        return object;
    };

    //复制不覆盖属性
    _T.applyIf = function (object, config) {
        var property;
        if (object) {
            for (property in config) {
                if (object[property] === undefined) {
                    object[property] = config[property];
                }
            }
        }
        return object;
    };

    var getFormId = function (field) {
        var parent = field.parentNode;
        while (true) {
            if (parent.tagName) {
                if (parent.tagName.toLowerCase() == 'body') {
                    return null;
                }
                if (parent.tagName.toLowerCase() == 'form') {
                    return parent.getAttribute("tid");
                }
            }
            parent = parent.parentNode;
        }
    };

    var findForm = function (field) {
        var formId = getFormId(field);
        if (formId != null) {
            var id = field.getAttribute("tid");
            _T.formFields[formId] = _T.formFields[formId] || [];
            _T.formFields[formId].push(_T.elements[id]);
        }
    };

    $(document).ready(function () {

        //文本对象集合
        var fields = [];

        // 遍历所有标签
        $("*").each(function (idx, el) {

            var tagName = el.tagName;

            //不是t标签 继续遍历
            if (tagName == null) {
                return true;
            }

            tagName = tagName.toUpperCase().replace(/^T\:/, '');

            // 该标签有定义转换创建函数
            if (typeof (_T.Ui[tagName]) == 'function') {

                var id = el.getAttribute("tid");
                if (typeof (_T.elements[id]) != 'undefined') {
                    return;
                }

                _T.elements[id] = new _T.Ui[tagName](el);

                if (tagName == "FIELD") {
                    fields.push(el)
                }

                return true;
            }
        });

        //查找fields的所属表单对象 并且关联上
        $(fields).each(function (field) {
            findForm(field);
        });

    });

})();